
/*
 * 文件名：MyShiro.java.
 * 描述：
 * 创建人: 龚洪亮
 * 创建时间：2017年8月29日
 */

package com.fiberhome.platform.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import com.fiberhome.platform.pojo.User;
import com.fiberhome.platform.service.UserService;


/**
 * @Description 
 * @author 龚洪亮
 * @version 2017年8月29日
 */

public class MyShiro extends AuthorizingRealm {

	@Autowired  
    private UserService userService;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		String loginName=(String) principalCollection.fromRealm(getName()).iterator().next();  
        //此处连库匹配了登录用户的数据，具体怎么做，需要根据个人需求而定
        User user=userService.findByName(loginName);
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();  
        //获取用户的角色名称
        info.setRoles(userService.getRolesName(user)); 
		return info;
	}

	
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authenticationToken) throws AuthenticationException {
		UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken;  
        //判断用户登录状态
        User user=userService.findByName(token.getUsername());  
        if(user!=null){  
            //保存用户登录信息到认证中
            return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());  
        }  
        return null;  
	}

}
